package com.hgyc.mom.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * Freemarker模板工具类
 * @author fwj
 * @since 2025/4/28
 */
public class FreeMarkerUtils {

    private static final Configuration CONFIG;

    static {
        CONFIG = new Configuration(Configuration.VERSION_2_3_33);
        CONFIG.setClassForTemplateLoading(FreeMarkerUtils.class, "/templates");
        CONFIG.setDefaultEncoding(StandardCharsets.UTF_8.name());
        CONFIG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIG.setLogTemplateExceptions(false);
    }

    public static String processTemplate(String templateName, Object model) throws IOException, TemplateException {
        Template template = CONFIG.getTemplate(templateName);
        StringWriter writer = new StringWriter();
        template.process(model, writer);
        return writer.toString();
    }

    /**
     * 解析字符串模板
     * @param templateStr 字符串模板
     * @param value 变量值
     * @return 解析结果
     * @throws IOException
     * @throws TemplateException
     */
    public static String processTemplateStr(String templateStr, Map<String, Object> value) throws IOException, TemplateException {
        Template template = new Template("sqlTemplate", new StringReader(templateStr), CONFIG);
        StringWriter out = new StringWriter();
        template.process(value, out);
        return out.toString();
    }

}
